/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package com.dc.gameserver.extComponents.utilsKit.util;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class StringUtil {
	public static final String CHECKEMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
	public static final String CHECKPASSWORD = "^[A-Za-z0-9]+$";
	private static final String HMAC_SHA1 = "HmacSHA1";

	public static String loadId(String path) {
		InputStream is = null;
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer(0);

		try {
			URL url = StringUtil.class.getClassLoader().getResource(path);
			is = url.openStream();
			reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
			String line = null;
			do {
				line = reader.readLine();
				if (line != null) {

					if (sb.length() > 0) {
						sb.append("\n");
					}
					sb.append(line);
				}
			} while (line != null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static boolean wirteString(String path, String value) {
		try {
			URL url = StringUtil.class.getClassLoader().getResource(path);

			File write = new File(url.toURI());
			BufferedWriter bw = new BufferedWriter(new FileWriter(write));
			if (value != null) {
				// 写文件
				bw.write(value); // 只适用Windows系统
			}
			bw.close();
			return true;
		} catch (FileNotFoundException e) { // 文件未找到
			System.out.println(e);
			return false;
		} catch (IOException e) {
			System.out.println(e);
			return false;
		} catch (URISyntaxException e) {
			return false;
		}
	}

	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}

	// 判断是不是中文
	public static boolean isChina(String str) {
		return str.matches("[\\u4E00-\\u9FA5]+");
	}

	public static int getNameSize(String content) {
		int count = 0;
		char[] c = content.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (isLetter(c[i])) {
				count++;
			} else {
				count += 2;
			}
		}

		return count;
	}

	// 判断是否半角
	public static boolean isEnna(String param) {

		char[] chs = param.toCharArray();
		for (int i = 0; i < chs.length; i++) {
			if (!(('\uFF61' <= chs[i]) && (chs[i] <= '\uFF9F'))
					&& !(('\u0020' <= chs[i]) && (chs[i] <= '\u007E'))) {
				if (!isChina(String.valueOf(chs[i]))) {
					return false;
				}
			}
		}
		return true;
	}

	public static Integer toInt(Object o) {
		Integer temp = 0;
		if (o != null) {
			String mintemp = o.toString();
			if (mintemp.indexOf(".") > 0) { //
				temp = Integer.parseInt(mintemp.substring(0, mintemp // 把小数位去掉
                        .indexOf("."))); //
			}
		}
		return temp;
	}

	public static String formatTime(Timestamp intime) {
		final String DATE_FORMATE = "yyyy-MM-dd";
		DateFormat df = new SimpleDateFormat(DATE_FORMATE);
		return df.format(intime);
	}

	public static String formatDataTime(Timestamp intime) {
		final String DATE_FORMATE = "yyyy-MM-dd HH:mm:ss";
		DateFormat df = new SimpleDateFormat(DATE_FORMATE);
		return df.format(intime);
	}
	
	public static String formatMsTime(Date date) {
		final String DATE_FORMATE = "yyyyMMddHHmmssSSS";
		DateFormat df = new SimpleDateFormat(DATE_FORMATE);
		return df.format(date);
	}

	public static Integer random(Integer pcent, Integer from, Integer to) {
		Integer ramNum = random(1, 10);
		if (ramNum > pcent - 1) {
			return random(from, to);
		}
		return 0;
	}

	public static Integer random(Integer from, Integer to) {
		Integer ramNum = 0;
		do {
			ramNum = new Random().nextInt(to);
		} while (ramNum < from || to < ramNum);

		return ramNum;
	}

	/**
	 * 写二进制文件
	 * 
	 * @param path
	 * @param bytedate
	 * @return
	 */
	public static boolean wirteByte(String path, byte[] bytedate) {
		File file = new File(path);

		FileOutputStream stream = null;
		try {
			if (!file.exists()) {
				if(!file.createNewFile()){
					return false;
				}
			}
			stream = new FileOutputStream(file);
			FileChannel channel = stream.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(bytedate.length);
			buffer.put(bytedate);
			buffer.flip();

			channel.write(buffer);
		} catch (FileNotFoundException e1) {

			e1.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return false;

	}
	
	/**
	 * 判断是否在某时间段内
	 * @param start 参数如2009-10-20 22:30:00
	 * @param end
	 * @return false-不在 true-在
	 */
	public static boolean betweenDate(String start,String end){
		final String DATE_FORMATE = "yyyy-MM-dd HH:mm:ss";
		try{
			Date nowDate = new Date();
			DateFormat df = new SimpleDateFormat(DATE_FORMATE);
			if(nowDate.before(df.parse(start)) || nowDate.after(df.parse(end)))
				return false;
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 判断某时间是否在某段时间内
	 * @param start
	 * @param end
	 * @param nowDate
	 * @return
	 */
	public static boolean betweenDate(String start,String end,Date nowDate){
		final String DATE_FORMATE = "yyyy-MM-dd HH:mm:ss";
		try{
			DateFormat df = new SimpleDateFormat(DATE_FORMATE);
			if(nowDate.before(df.parse(start)) || nowDate.after(df.parse(end)))
				return false;
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	/**
     * bytes转换成十六进制字符串
     */
	public static String byte2HexStr(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        String stmp = "";
        for (int n=0;n<b.length;n++) {
            stmp=(Integer.toHexString(b[n] & 0XFF));
            if (stmp.length()==1) 
                buffer.append("0").append(stmp);
            else 
            	buffer.append(stmp);
        }
        return buffer.toString().toLowerCase();
    }

	/**
	 * 生成随机长度为N的密钥
	 * @param pwd_len
	 * @return
	 */
	public static String genRandomNum(int pwd_len) {
		// 35是因为数组是从0开始的，26个字母+10个数字
		final int maxNum = 36;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
				'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
				'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwd_len) {
			// 生成随机数，取绝对值，防止生成负数，

			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1

			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}

		return pwd.toString();
	}
	
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
			|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
	
			|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
	
			|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
	
			|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
	
			|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}

		return false;

	}

	/**
	 * 获得单字符长度(1中文=2单字符)
	 * @param strName
	 * @return
	 */
	public static int charLen(String strName) {
		char[] ch = strName.toCharArray();
		int count = 0;
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isChinese(c) == true) {
				count = count + 2;
			} else {
				count++;
			}
		}
		return count;
	}

	/**
	 * 截取长度为limit字符的字符串
	 * @param limit
	 * @return
	 */
	public static String contentLimit(String content,int limit){
		char[] ch = content.toCharArray();
		int count = 0;
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if(isChinese(c) == true && count <= limit - 2) {
				count = count + 2;
				buffer.append(c);
			}else if(count <= limit - 1){
				buffer.append(c);
				count++;
			}else{
				break;
			}
		}
		return buffer.toString();
	}
	
//	 public static String getSignature(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException {
//		 SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1);
//		 Mac mac = Mac.getInstance(HMAC_SHA1);
//		 mac.init(signingKey);
//		 byte[] rawHmac = mac.doFinal(data);
//		 return (new sun.misc.BASE64Encoder()).encode(rawHmac);
//	}
	
	public static void main(String args[]){
		String str = "点击打开发达反对反对的是适当1315342thrgkrjhs1jopjfodvdj2p方式的合法手段ikhfds范德萨仿盛大";
		System.out.println(contentLimit(str,60));
	}
	
}
